import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import UnoCSS from "unocss/vite";
import AutoImport from "unplugin-auto-import/vite";
import IconsResolver from "unplugin-icons/resolver";
import Icons from "unplugin-icons/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { createHtmlPlugin } from "vite-plugin-html";

const pathSrc = path.resolve(__dirname, "./src");

const mode = process.env.VITE_NODE_ENV || "development";

const getEnvironmentVariable = (key: string, mode: string): string => {
  return loadEnv(mode, process.cwd())[key];
};

export default defineConfig({
  plugins: [
    vue(),
    createHtmlPlugin({
      inject: {
        data: {
          title: getEnvironmentVariable("VITE_GLOB_APP_TITLE", mode),
        },
      },
    }),
    UnoCSS(),
    AutoImport({
      imports: ["vue", "vue-router", "pinia"],
      dirs: ["src/components"],
      eslintrc: {
        enabled: true,
        filepath: path.resolve(pathSrc, ".eslintrc-auto-import.json"),
      },
      resolvers: [
        ElementPlusResolver(),
        IconsResolver({
          prefix: "Icon",
        }),
      ],
      dts: path.resolve(pathSrc, "auto-imports.d.ts"),
    }),
    Components({
      resolvers: [
        IconsResolver({
          enabledCollections: ["ep"],
        }),
        ElementPlusResolver(),
      ],
      dts: path.resolve(pathSrc, "components.d.ts"),
    }),
    Icons({
      autoInstall: true,
    }),
  ],
  server: {
    host: true,
    port: 3000,
    hmr: true,
    proxy: {
      [getEnvironmentVariable("VITE_APP_BASE_API", mode)]: {
        target: getEnvironmentVariable("VITE_APP_SERVER_URL", mode),
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  resolve: {
    alias: {
      "@": pathSrc,
    },
  },
  build: {
    minify: "terser",
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    rollupOptions: {
      output: {
        chunkFileNames: "static/js/[name]-[hash].js",
        entryFileNames: "static/js/[name]-[hash].js",
        assetFileNames: "static/[ext]/[name]-[hash].[ext]",
        manualChunks: {
          vue: ["vue", "vue-router"],
          pinia: ["pinia"],
          elementPlus: ["element-plus"],
          axios: ["axios"],
        },
      },
    },
  },
});
